import { IHttpResponse, IObject } from "@/types/interface";
import http from "../utils/http";
import axios, { AxiosInstance } from "axios";
import app from "@/constants/app";
import { getToken } from "@/utils/cache";

interface DownloadFileResponse {
  data: Blob;
  headers: {
    "content-disposition": string;
  };
}

const apiClient: AxiosInstance = axios.create({
  baseURL: app.api,
  timeout: app.requestTimeout,
});

/**
 * 常用CRUD
 */
export default {
  /**
   * 删除
   * @param path
   * @param params
   * @returns
   */
  delete(path: string, params: IObject): Promise<IHttpResponse> {
    return http({
      url: path,
      data: params,
      method: "DELETE",
    });
  },
  get(
    path: string,
    params?: IObject,
    headers?: IObject
  ): Promise<IHttpResponse> {
    return new Promise((resolve, reject) => {
      http({
        url: path,
        params,
        headers,
        method: "GET",
      })
        .then(resolve)
        .catch((error) => {
          if (error !== "-999") {
            reject(error);
          }
        });
    });
  },
  put(
    path: string,
    params?: IObject,
    headers?: IObject
  ): Promise<IHttpResponse> {
    return http({
      url: path,
      data: params,
      headers: {
        "Content-Type": "application/json;charset=UTF-8",
        ...headers,
      },
      method: "PUT",
    });
  },
  /**
   * 通用post方法
   * @param path
   * @param body
   * @returns
   */
  post(
    path: string,
    body?: IObject,
    headers?: IObject
  ): Promise<IHttpResponse> {
    return http({
      url: path,
      method: "post",
      headers: {
        "Content-Type": "application/json;charset=UTF-8",
        ...headers,
      },
      data: body,
    });
  },
  async downloadFile(path: string) {
    try {
      const response = await axios({
        url: app.api + path,
        method: "GET",
        responseType: "arraybuffer", // 重要：指定返回类型为blob
        headers: {
          token: getToken(),
          'Content-Type': 'application/octet-stream',
        },
      });

      console.log('response', response);

      // const url = window.URL.createObjectURL(new Blob([response.data]));
      // const link = document.createElement("a");
      // link.href = url;
      // link.setAttribute("download", "filename.xlsx"); // 修改为你的文件名和扩展名
      // document.body.appendChild(link);
      // link.click();

      // // 清理工作：移除创建的链接和释放URL对象
      // document.body.removeChild(link);
      // window.URL.revokeObjectURL(url);
    } catch (error) {
      console.error("下载文件失败:", error);
    }
  },
};
